package cn.iocoder.yudao.module.iot.util;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;

public class SmsUtil {


    @Value("${sms.accessKeySecret}")
    private String accessKeyId;

    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * desc:短信工具，发送报警短信
     * @author:fuzhifei
     * @date:2023/11/27 15:18
     */


    private final static Logger logger = LoggerFactory.getLogger(SmsUtil.class);

    /**
     * desc: 工具类，通过阿里云发送短信
     * @author:fuzhifei
     * @date:2023/11/22 17:29
     * @param phoneNum 用户手机号
     * @param templateCode  短信模板编号
     * @param code 模板参数
     * @return boolean 返回发送结果
     */

    public static boolean send(String phoneNum, String templateCode, Map code) {
        String id="LTAI5t728UdoYTcrUZrR3tpP";
        String sec="MSmtZnIXlWoYpQJRPt2ZKVPdvDgGQM";
        //连接阿里云服务器
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", id,sec);
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");//此处禁止修改
        request.setSysVersion("2017-05-25");//此处禁止修改
        request.setSysAction("SendSms");
        //自定义的参数（手机号，验证码，签名，模版）
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "晨灵科技");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info(response.getData());
            // 记录日志
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
            logger.error("send sms error:"+e.getErrMsg());
        } catch (ClientException e) {
            e.printStackTrace();
            logger.error("send sms error:"+e.getErrMsg());
        }
        return false;
    }


    public static void main(String[] args) {
        String phoneNum="13343432683";
        String templateCode="SMS_463895057";
        Map code=new HashMap();
        code.put("warnType","温度");
        code.put("type","温度");
        code.put("value","90度");
        send(phoneNum, templateCode,code);
    }
}
